define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'selectpage'], function ($, undefined, Backend, Table, Form, selectPage) {

    var newhouse_id = Fast.api.query('newhouse_id');
    var structure_id = Fast.api.query('structure_id');
    var building_id = Fast.api.query('building_id');
    var ids = Fast.api.query('ids');

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'newhouse/layout/index' + location.search,
                    add_url: 'newhouse/layout/add/newhouse_id/' + newhouse_id + '/structure_id/' + structure_id + '/building_id/' + building_id,
                    edit_url: 'newhouse/layout/edit/newhouse_id/' + newhouse_id + '/structure_id/' + structure_id + '/building_id/' + building_id,
                    del_url: 'newhouse/layout/del',
                    multi_url: 'newhouse/layout/multi',
                    table: 'newhouse_layout',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                queryParams: function (params) {
                    var filter = params.filter ? JSON.parse(params.filter) : {};
                    var op = params.op ? JSON.parse(params.op) : {};

                    if (newhouse_id) {
                        filter['newhouse_id'] = newhouse_id;
                        op['newhouse_id'] = '=';
                    }
                    if (structure_id) {
                        filter['structure_id'] = structure_id;
                        op['structure_id'] = '=';
                    }
                    if (building_id) {
                        filter['newhouse_layout.building_ids'] = building_id;
                        op['newhouse_layout.building_ids'] = 'FIND_IN_SET';
                    }
                    params.filter = JSON.stringify(filter);
                    params.op = JSON.stringify(op);
                    return params;
                },
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'newhousestructure.category_id', title: __('Type'), formatter: Controller.api.formatter.type},
                        {field: 'newhousestructure.category_id', title: __('Type')+'属性', formatter: Controller.api.formatter.category},
                        {field: 'title', title: __('Title')},
                        {field: 'url', title: __('Url'), operate: false, formatter: Table.api.formatter.images, events: Table.api.events.image},
                        {field: 'floorage', title: __('Floorage')},
                        {field: 'innerarea', title: __('Innerarea')},
                        {field: 'usearea', title: __('Usearea')},
                        {field: 'recommend', title: __('Recommend'), searchList: {"0":__('Recommend 0'),"1":__('Recommend 1')}, formatter: Controller.api.formatter.recommend},
                        {field: 'flag', title: __('Flag'), searchList: {"0":__('Flag 0'),"1":__('Flag 1')}, formatter: Controller.api.formatter.flag},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'admin.nickname', title: __('Admin.nickname')},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'newhouse/layout/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'title', title: __('Title'), align: 'left'},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '130px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'newhouse/layout/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'newhouse/layout/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            if (structure_id === 'null') {
                $("#c-structure_id").selectPage({
                    params: function() {
                        return {custom: {newhouse_id: newhouse_id}};
                    },
                    eAjaxSuccess: function(data) {
                        data.list = typeof data.rows !== 'undefined' ? data.rows : (typeof data.list !== 'undefined' ? data.list : []);
                        data.totalRow = typeof data.total !== 'undefined' ? data.total : (typeof data.totalRow !== 'undefined' ? data.totalRow : data.list.length);
                        return data;
                    },
                    eSelect : function(data) {
                        location.href = 'newhouse/layout/add/newhouse_id/' + newhouse_id + '/structure_id/' + data.id + '/building_id/' + building_id + '?dialog=1';
                    }
                });
            }
            Controller.api.bindevent();
        },
        edit: function () {
            console.log(structure_id);
            if (structure_id === 'null') {
                $("#c-structure_id").selectPage({
                    params: function() {
                        return {custom: {newhouse_id: newhouse_id}};
                    },
                    eAjaxSuccess: function(data) {
                        location.href = 'newhouse/layout/edit/newhouse_id/' + newhouse_id + '/structure_id/' + data.list[0].id + '/building_id/' + building_id + '/ids/' + ids + '?dialog=1';
                    }
                });
            } else {
                Controller.api.bindevent();
            }

        },
        api: {
            bindevent: function () {
                $("#c-structure_id").data("params", function (obj) {
                    return {custom: {newhouse_id: newhouse_id}};
                });
                $("#c-building_ids").data("params", function (obj) {
                    return {custom: {structure_id: $("#c-structure_id").val(),pid: ["gt", 0]}};
                });
                $("#c-structure_id").change(function () {
                    $("#c-building_ids").selectPageClear();
                });

                Form.api.bindevent($("form[role=form]"));

                var url_input = $('#plupload-url').data("input-id") ? $('#plupload-url').data("input-id") : "";
                var url_preview = $('#plupload-url').data("preview-id") ? $('#plupload-url').data("preview-id") : "";
                if (url_preview) {
                    $(document.body).off("click", "#" + url_preview + " .btn-trash");
                    // 监听事件
                    $(document.body).on("fa.preview.change", "#" + url_preview, function () {
                        var urlArr = [];
                        $("#" + url_preview + " [data-url]").each(function (i, j) {
                            urlArr.push($(this).data("url"));
                        });
                        if (url_input) {
                            $("#" + url_input).val(urlArr.join(","));
                        }
                    });
                    // 移除按钮事件
                    $(document.body).on("click", "#" + url_preview + " .btn-trash", function () {
                        var that = $(this);
                        var path = $("#" + url_preview + " [data-url]");
                        Layer.confirm('是否删除该图片？（删除后不可恢复）',
                            {icon: 3, title: __('Warning'), offset: 0, shadeClose: true},
                            function (index) {
                                var options = {
                                    url: 'newhouse/layout/delUpload',
                                    data: {
                                        path: path.data("url")
                                    }
                                }
                                Fast.api.ajax(options, function () {
                                    that.closest("li").remove();
                                    $("#" + url_preview).trigger("fa.preview.change");
                                    Layer.close(index);
                                });
                            }
                        );
                    });
                }
            },
            formatter: {
                recommend: function (value, row, index) {
                    return '<a class="btn-change text-success" data-url="'+$.fn.bootstrapTable.defaults.extend.multi_url+'" data-id="' + row.id + '" data-params="recommend=' + (row.recommend == '0' ? '1' : '0') + '"><i class="fa ' + (row.recommend == '0' ? 'fa-toggle-off' : 'fa-toggle-on') + ' fa-2x"></i></a>';
                },
                flag: function (value, row, index) {
                    return '<a class="btn-change text-success" data-url="'+$.fn.bootstrapTable.defaults.extend.multi_url+'" data-id="' + row.id + '" data-params="flag=' + (row.flag == '0' ? '1' : '0') + '"><i class="fa ' + (row.flag == '0' ? 'fa-toggle-off' : 'fa-toggle-on') + ' fa-2x"></i></a>';
                },
                type: function (value, row, index) {
                    var type;
                    switch (row.newhousestructure.category_id) {
                        case 1:
                            type = '住宅';
                            break;
                        case 3:
                            type = '公寓';
                            break;
                        case 4:
                            type = '写字楼';
                            break;
                        case 6:
                            type = '商铺';
                            break;
                        case 7:
                            type = '别墅';
                            break;
                    }
                    return type;
                },
                category: function (value, row, index) {
                    var type;
                    switch (row.newhousestructure.category_id) {
                        case 1:
                            type = row.htype_text;
                            break;
                        case 3:
                            type = row.atype_text;
                            break;
                        case 4:
                            type = row.otype_text;
                            break;
                        case 6:
                            type = row.stype_text;
                            break;
                        case 7:
                            type = row.vtype_text;
                            break;
                    }
                    return type;
                }
            }
        }
    };
    return Controller;
});
